package com.feng.security.filter;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.feng.common.exceptions.PathException;
import com.feng.common.utils.SecurityUtil;
import com.feng.security.utils.JwtUtils;
import com.feng.security.utils.RsaUtils;
import com.feng.security.vo.UserVO;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.List;

/**
 * @author feng
 * @describe
 */
public class GlobalUserAuthFilter extends BasicAuthenticationFilter {
    public GlobalUserAuthFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String method = request.getMethod();
        String uri = request.getRequestURI();
        if ("options".equalsIgnoreCase(method)) {
            chain.doFilter(request, response);
            return;
        }
        if (Arrays.asList(SecurityUtil.RELEASER).contains(uri)) {
            chain.doFilter(request, response);
            return;
        }
        //验证token
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            throw new RuntimeException("令牌不能为空");
        }
        PublicKey publicKey = null;
        try {
            byte[] bytes = RsaUtils.readByByte(new ClassPathResource("key/pub").getInputStream());
            publicKey = RsaUtils.getPublicKey(bytes);
        } catch (Exception e) {
            throw new PathException("服务器繁忙");
        }
        UserVO userVO = JwtUtils.getInfoFromToken(token, publicKey, UserVO.class);
        String join = StrUtil.join(StrPool.COMMA, userVO.getRoleList(), userVO.getMenuList());
        join += ",ROLE_";
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(join);
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userVO, null, grantedAuthorities);
        //securityContext存储用户权限
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request, response);
    }
}
